<?php

namespace Biz\service\salesRebate;

use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\salesRebate\SalesAccount as mSalesAccount;
use Biz\model\salesRebate\SalesCompany as mSalesCompany;
use Biz\model\salesRebate\SalesCoupon as mSalesCoupon;
use Biz\model\salesRebate\SalesCouponMap as mSalesCouponMap;
use Biz\model\salesRebate\SalesCouponSingle as mSalesCouponSingle;
use Biz\model\salesRebate\SalesOrder as mSalesOrder;
use Biz\model\salesRebate\SalesOrderLog as mSalesOrderLog;
use Biz\model\salesRebate\SalesPersonal as mSalesPersonal;
use Biz\model\salesRebate\SalesWithdrawalRecord as mSalesWithdrawalRecord;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\module\Classes\SalesRebate as cSalesRebate;
use Biz\pockets\constInterface\SalesRebateConfig;
use Biz\pockets\excel\DownExcel;
use Biz\pockets\excel\ReadExcel;
use Biz\service\salesRebate\SalesWithdrawal as sSalesWithdrawal;
use Biz\tools\ShopArea;
use Doraemon\model\Phone;
use Doraemon\model\Phone as mPhone;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\service\User;
use hhz\constant\basic\findPhoneScene;

/**
 * @deprecated
 */
class SalesRebate
{
    const EXCEL_HEADER_MAP = [
        '手机号' => 'phone',
        '所在地区' => 'belongs',
    ];

    public static function getExcelData($file)
    {
        $data = (new ReadExcel($file))->getExcelData(0, self::EXCEL_HEADER_MAP, false);
        return $data;

    }

    public static function checkExcelData($data)
    {
        if (empty($data)) {
            throw new \Exception('导入的数据为空');
        }
        //检查每项数据的必要性
        $i = 1;
        $error = [];
        $result = [];
        foreach ($data as $key => &$item) {
            if (!empty($item['phone'])) {
                $i += 1;
                try {
                    $item['phone'] = trim($item['phone']);
                    $item['belongs'] = $item['belongs'] == "上海" ? 1 : 2;
                    $isValid = self::createCoupon($item);
                    if (!$isValid['status']) {
                        $error[$i] = "第{$i}行,手机号:" . $item['phone'] . ",错误信息:" . $isValid['msg'];
                    }
                    unset($isValid);
                } catch (\Exception $e) {
                    throw new \Exception("第{$i}行,错误信息:" . $e->getMessage());
                }
            }
        }
        if (!empty($error)) {
            throw new \Exception(implode(' || ', $error));
        }


        return $result;
    }

    /**
     * 根据券码获取归属地和是否设计师券
     * @param $code
     * @return bool
     */
    public static function getCouponInfo($code_id)
    {
        $data = [];
        try {
            $coupon = mCouponConfig::get([
                'coupon_code',
                'belongs'
            ], [
                'coupon_id' => $code_id,
                'channel' => mCouponConfig::COUPON_CHANNEL_THE_PARAGRAPH
            ]);
            if ($coupon) {
                $salesCoupon = mSalesCoupon::getOneByWhere([
                    'id',
                    'uid',
                    'belong_area'
                ],
                    [
                        'OR' => [
                            'person_coupon_code' => $coupon['coupon_code'],
                            'company_coupon_code' => $coupon['coupon_code']
                        ]
                    ]
                );
                if (empty($salesCoupon)) {
                    $salesCoupon = mSalesCouponSingle::getOneByWhere('*', ['coupon_code' => $coupon['coupon_code']]);
                    if ($salesCoupon) {
                        $salesCoupon['belong_area'] = mSalesCoupon::getOneByWhere('belong_area', ['uid' => $salesCoupon['uid']]);
                    }
                }
                if ($salesCoupon) {
                    //设计师券
                    $data = [
                        'area' => mCouponConfig::$belongs_en[$salesCoupon['belong_area']],
                        'is_designer' => true
                    ];
                    $userPhone = Phone::getDecryptPhoneByUid($salesCoupon['uid'], findPhoneScene::SHOP_ORDER_PHONE);
                    $data['phone'] = $userPhone;
                    $data['encrypt_phone'] = $userPhone;
                } else {
                    //节选普通券
                    $data = [
                        'area' => mCouponConfig::$belongs_en[$coupon['belongs']],
                        'is_designer' => false
                    ];
                }
            }
            return $data;
        } catch (\Exception $e) {
            return $data;
        }
    }

    /**
     * 是否是白名单里的有效用户
     * @param $uid
     * @return bool
     */
    public static function isVaild($uid)
    {
        //未启用不可创建任何信息
        $user = mSalesCoupon::getCache([$uid]);
        if (!empty($user)) {
            if ($user[0]['status'] != 1) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 创建白名单
     * @param $params
     * @return mixed
     */
    public static function createCoupon($params, $isCheck = true)
    {
        if ($isCheck) {
            try {
                if (isset($params['phone'])) {
                    $phone = PhoneCrypto::encrypt($params['phone'], PhoneCrypto::CLIENT_SHOP_ADMIN, PhoneCrypto::VERSIN);
                    $params['uid'] = mPhone::getUidByPhone($phone);
                    unset($params['phone']);
                }
                if (isset($params['uid']) && $params['uid']) {
                    $user = current(cSalesRebate::getUser(['uid' => $params['uid']]));
                } else {
                    $user = false;
                }
            } catch (\Exception $e) {
                $user = false;
            }
            if (!$user) {
                $result['status'] = false;
                $result['msg'] = '用户不存在';
                return $result;
            } else {
                //验证手机号
                if (empty($user['telephone'])) {
                    $result['status'] = false;
                    $result['msg'] = '用户没有绑定电话';
                    return $result;
                }
            }
        }

        return mSalesCoupon::create($params);
    }

    /**
     * 生成提现单
     * @param $uid
     * @param $type 提现类别 1个人 2公司
     * @param $amount 提现金额
     * @return array
     */
    public static function createBill($uid, $type = 1, $amount = 0)
    {
        if (!self::isVaild($uid)) {
            return false;
        }

        $account = cSalesRebate::getAccount($uid, $type);

        if (empty($account)) {
            return false;
        } else {
            $bank = $account;
        }

        if ($type == 1) {
            $result = sSalesWithdrawal::createPersonalBill($uid, $bank);
        } else {
            if ($amount > 0) {
                $result = sSalesWithdrawal::createCompanyBill($uid, $amount, $bank);
            } else {
                return false;
            }
        }

        if ($result && !empty($result['status'])) {
            $result['status_remark'] = cSalesRebate::getStatus($result['status'], 3, $type);
        }

        return $result;
    }

    public static function getAppSaleAccount($uid)
    {
        $data['sale_amount'] = '0';//累计带货金额
        $data['all_rebate'] = '0';//预计返佣收入
        $data['account_rebate'] = '0';//已确认佣金
        $list = mSalesOrder::getAllByWhere('*', ['uid' => $uid, 'type' => mSalesAccount::TYPE_APP]);
        $orderNos = array_column($list, 'order_no');
        $orderData = mOrder::getOrderByWhere(
            'select',
            ['order_no', 'pay_way', 'pay_no'],
            ['order_no' => $orderNos, 'pay_way[!]' => '', 'pay_no[!]' => '']
        );
        $orderData = array_column($orderData, NULL, 'order_no');
        foreach ($list as $row) {
            if (isset($orderData[$row['order_no']])) {
                $data['sale_amount'] = bcadd($data['sale_amount'], $row['sale_amount'], 2);
                $accountRebate = 0;
                $allRebate = 0;
                if (in_array($row['status'], [mSalesOrder::STATUS_NORMAL, mSalesOrder::STATUS_ACCOUNTED])) {
                    $allRebate = bcmul($row['sale_amount'], ($row['rate'] / 100), 2);
                }
                if ($row['status'] == mSalesOrder::STATUS_ACCOUNTED) {
                    $accountRebate = bcmul($row['sale_amount'], ($row['rate'] / 100), 2);
                }
                $data['all_rebate'] = bcadd($data['all_rebate'], $allRebate, 2);
                $data['account_rebate'] = bcadd($data['account_rebate'], $accountRebate, 2);
            }
        }
        $result['rebate'] = $data;
        return $result;
    }

    /**
     * 获取个人账户相关的信息
     * @param $uid
     * @return array
     */
    public static function getAccount($uid, $type = '', $status = '')
    {
        $user = mSalesCoupon::getCache([$uid]);
        unset($user[0]['id'], $user[0]['admin_id'], $user[0]['edittime'], $user[0]['person_coupon_id'], $user[0]['company_coupon_id']);
        if (!empty($user) && $user[0]['status'] != 9) {
            $result['status'] = $user[0]['status'];
            $result['status_remark'] = cSalesRebate::getStatus($user[0]['status'], 1);
        } else {
            $result['status'] = -1;
            $result['status_remark'] = '非返佣用户';
            return $result;
        }


        //获取账户信息
        if ($type <> '') {
            if ($type == 1) {
                $result['account_person'] = cSalesRebate::getAccount($uid, 1, $status);
            } else if ($type == 2) {
                $result['account_company'] = cSalesRebate::getAccount($uid, 2, $status);
            }
        } else {
            $result['account_person'] = cSalesRebate::getAccount($uid, 1, $status);
            $result['account_company'] = cSalesRebate::getAccount($uid, 2, $status);
        }

        if (isset($result['account_person'])) {
            $result['account_person']['status_remark'] = cSalesRebate::getStatus($result['account_person']['status'], 2, 1);
        }
        if (isset($result['account_company'])) {
            //获取公司配置信息
            $result['company'] = SalesRebateConfig::COMPANY_INFO;
            //发票模版
            $result['account_company']['invoice_url'] = 'https://img.haohaozhu.cn/Op-imageShow/973f131300n00C100po1f1w?iv=1';
            $result['account_company']['status_remark'] = cSalesRebate::getStatus($result['account_company']['status'], 2, 2);
        }

        //获取个人和公司提现码
        $coupon = $user[0];
        if (!empty($coupon) && $coupon['status'] == mSalesCoupon::STATUS_OPEN) {
            $result['coupon'] = $coupon;
            $result['coupon']['status_remark'] = cSalesRebate::getStatus($result['coupon']['status'], 1);
        }

        //获取金额和比例信息
        $result['rebate'] = cSalesRebate::getRatio($uid);
        $result['uid'] = $uid;

        //获取提现单数量
        $apply = mSalesWithdrawalRecord::getOneByWhere(
            [
                'id',
                'addtime',
                'withdrawal_code',
                'status'
            ],
            [
                'type' => 2,
                'uid' => $uid,
                'status' => mSalesWithdrawalRecord::STATUS_NORMAL,
                'ORDER' => ['id' => 'DESC']
            ]
        );
        $result['company_apply'] = $apply;

        $result['apply_num'] = mSalesWithdrawalRecord::count([
            'status' => mSalesWithdrawalRecord::STATUS_NORMAL,
            'uid' => $uid
        ]);


        return $result;
    }

    /**
     * 获取申请记录
     */
    public static function getOneApply($where)
    {
        $data = mSalesWithdrawalRecord::getOneByWhere(
            [
                'bank_name',
                'bank_no',
                'id_card_no',
                'name',
                'telephone',
                'type',
                'uid',
                'withdrawal_amount',
                'withdrawal_code',
                'status',
                'addtime'
            ],
            $where
        );
        $data['status_remark'] = cSalesRebate::getStatus($data['status'], 3, $data['type']);
        return $data;
    }

    /**
     * 获取申请记录
     */
    public static function getApply($where, $page, $pagesize)
    {
        $result = $data = [];
        $data = mSalesWithdrawalRecord::getAllByWhere('*', $where);
        if ($data) {
            $data = array_map(
                function ($_data) {
                    $_data['status_remark'] = cSalesRebate::getStatus($_data['status'], 3, $_data['type']);
                    //获取剩余时间
                    if ($_data['type'] == mSalesWithdrawalRecord::TYPE_COMPANY) {
                        $addtime = date('Y-m-d', strtotime($_data['addtime']));
                        $endtime = strtotime($addtime . '+30 day');
                        $checketime = strtotime($addtime . '+35 day');
                        $curtime = time();
                        if ($_data['status'] == 0) {
                            $_data['last_days'] = round(($endtime - $curtime) / 3600 / 24);
                        } else if ($_data['status'] == 1) {
                            $_data['last_days'] = round(($checketime - $curtime) / 3600 / 24) < 5 ? round(($checketime - $curtime) / 3600 / 24) : 5;
                        }
                    }
                    return $_data;
                },
                $data
            );
        }

        $result['list'] = $data;
        unset($where['ORDER'], $where['LIMIT']);
        $result['is_over'] = bcsub(bcdiv(mSalesWithdrawalRecord::count('*', $where), $pagesize), $page) > 0 ? 0 : 1;
        return $result;
    }


    /**
     * 获取账户订单
     * @param $where
     * @param int $page
     * @param int $pagesize
     * @return array
     */
    public static function getAppSaleOrder($where, $page = 0, $pageSize = 30)
    {
        $result = $data = [];
        $list = [];
        $page = $page ? $page : 1;
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where['LIMIT'] = $limit;
        $where['ORDER'] = ['addtime' => 'DESC'];
        $data = mSalesOrder::getAllByWhere('*', $where);
        if ($data) {
            $uids = array_column($data, 'uid');
            $consumerUids = array_column($data, 'consumer_uid');
            $uids = array_merge($uids, $consumerUids);
            $users = User::getBatchBasicUserInfo($uids);
            $users = array_column($users, null, 'uid');

            $orderNos = array_column($data, 'order_no');
            $orderData = mOrder::getOrderByWhere(
                'select',
                '*',
                ['order_no' => $orderNos, 'pay_way[!]' => '', 'pay_no[!]' => '']
            );
            $orderData = array_column($orderData, NULL, 'order_no');

            //获取商品的信息
            $goods = array_column($data, 'goods_id');
            $goods = mGoodsBasicInfo::getInfoList($goods);
            $goods = array_column($goods, NULL, 'goods_id');
            foreach ($data as $key => $row) {
                if (isset($orderData) && isset($orderData[$row['order_no']])) {
                    $row['status_remark'] = cSalesRebate::getStatus($row['status'], 4, $row['type']);
                    $row['type_remark'] = SalesRebateConfig::UID_TYPE[$row['type']];
                    $row['coupon'] = '';
                    if (isset($goods[$row['goods_id']])) {
                        $row['goods_title'] = $goods[$row['goods_id']]['title'];
                        $row['goods_img_url'] = $goods[$row['goods_id']]['spec_img_url'];
                    }
                    $row['nick'] = isset($users[$row['uid']]) ? $users[$row['uid']]['nick'] : '';
                    $row['consumer_nick'] = isset($users[$row['consumer_uid']]) ? $users[$row['consumer_uid']]['nick'] : '';
                    $row['order_status_desc'] = '';
                    $row['order_addtime'] = '';
                    //返佣金额
                    if (in_array($row['status'], [mSalesOrder::STATUS_INVALID, mSalesOrder::STATUS_DELETE])) {
                        $row['rebate'] = 0;
                    } else {
                        $row['rebate'] = bcmul($row['sale_amount'], $row['rate'] / 100, 2);
                    }
                    $row['order_addtime'] = $orderData[$row['order_no']]['addtime'];
                    $row['order_status_desc'] = self::getSaleOrderStatus($orderData[$row['order_no']]['status'], $row['status']);
                    $list[] = $row;
                }
            }
        }
        $count = mSalesOrder::count('*', $where);
        $isOver = ($page * $pageSize >= $count) ? 1 : 0;
        $result['list'] = $list;
        $result['is_over'] = !empty($list) ? $isOver : 1;
        $result['total'] = !empty($list) ? $count : 0;
        return $result;
    }

    private static function getSaleOrderStatus($orderStatus, $salesOrderStatus)
    {
        $status = '';
        switch ($orderStatus) {
            case mOrder::STATUS_WAIT_SEND:
                $status = '待发货';
                if ($salesOrderStatus == mSalesOrder::STATUS_INVALID) {
                    $status = '交易关闭';
                }
                break;
            case mOrder::STATUS_SEND_OUT:
            case mOrder::STATUS_SEND_PART_OUT:
                $status = '待收货';
                if ($salesOrderStatus == mSalesOrder::STATUS_INVALID) {
                    $status = '交易关闭';
                }
                break;
            case mOrder::STATUS_SUCCESS:
                if ($salesOrderStatus == mSalesOrder::STATUS_NORMAL) {
                    $status = '交易成功 未入账';
                } else if ($salesOrderStatus == mSalesOrder::STATUS_ACCOUNTED) {
                    $status = '佣金已入账';
                } else if ($salesOrderStatus == mSalesOrder::STATUS_INVALID) {
                    $status = '交易关闭';
                }
                break;
            case mOrder::STATUS_CLOSE:
                if ($salesOrderStatus == mSalesOrder::STATUS_INVALID) {
                    $status = '交易关闭';
                } else if ($salesOrderStatus == mSalesOrder::STATUS_ACCOUNTED) {
                    $status = '佣金已入账';
                }
                break;
        }
        return $status;
    }

    /**
     * 获取账户订单
     * @param $where
     * @param int $page
     * @param int $pagesize
     * @param string $step
     * @param array $params
     * @param bool $isAdmData 是否后台的数据
     * @return array
     */
    public static function getOrder($where, $page = 0, $pagesize = 0, $step = '', $params = [], $isAdmData = false)
    {
        if (!empty($params)) {
            $user = cSalesRebate::getUser($params);
            if (!empty($user)) {
                $userId = array_column($user, 'uid');
                $where['uid'] = $userId;
            }
        }

        $result = $data = [];
        if ($step <> '') {
            switch ($step) {
                case 1:
                    $where['status'] = mSalesOrder::STATUS_ACCOUNTED;
                    break;
                case 2:
                case 3:
                    $where['status'] = mSalesOrder::STATUS_NORMAL;
                    break;
                case 4:
                    $where['status'] = mSalesOrder::STATUS_INVALID;
                    break;
            }
        }
        $data = mSalesOrder::getAllByWhere('*', $where);

        if ($data) {
            $orderNo = array_column($data, 'order_no');
            //未入账要看是否付款了，付款的才显示
            if ($where['status'] == 0) {
                $orders = mOrder::getOrderByWhere(
                    'select',
                    [
                        'order_no',
                        'status'
                    ],
                    [
                        'order_no' => $orderNo,
                        'status[>]' => mOrder::STATUS_NORMAL
                    ]
                );
                $orders = array_column($orders, 'order_no');
                $data = array_filter($data, function ($_data) use ($orders) {
                    if (in_array($_data['order_no'], $orders)) {
                        return $_data;
                    }
                });
                $orderNo = array_column($data, 'order_no');
            }
        }
        if ($data) {
            //获取订单收货状态
            $orderData = $order = [];
            if ($step <> '') {
                switch ($step) {
                    case 2:
                        $orderwhere['status'] = mOrder::STATUS_SUCCESS;
                        break;
                    case 3:
                        $orderwhere['status'] = [
                            mOrder::STATUS_WAIT_SEND,
                            mOrder::STATUS_SEND_OUT,
                            mOrder::STATUS_SEND_PART_OUT
                        ];
                        break;
                }
                $orderwhere['order_no'] = $orderNo;
                $orderData = mOrder::getOrderByWhere('select', '*', $orderwhere);
                $order = array_column($orderData, 'order_no');
                $orderData = array_column($orderData, NULL, 'order_no');
            }
            //获取返券码
            $coupon = mSalesCoupon::getCache(array_column($data, 'uid'));
            $coupon = $coupon ? array_column($coupon, NULL, 'uid') : [];

            $couponIds = array_column($data, 'coupon_id');
            $singleCoupon = mSalesCouponSingle::getAllByWhere('*', ['coupon_id' => $couponIds]);
            $singleCoupon = array_column($singleCoupon, NULL, 'coupon_id');

            //获取商品的信息
            $goods = array_column($data, 'goods_id');
            $goods = mGoodsBasicInfo::getInfoList($goods);
            $goods = array_column($goods, NULL, 'goods_id');
            //用户姓名
            if (empty($params)) {
                $user = cSalesRebate::getUser(['uid' => array_column($data, 'uid')]);
            }
            foreach ($data as $_k => &$_v) {
                $_v['status_remark'] = cSalesRebate::getStatus($_v['status'], 4, $_v['type']);
                $_v['type_remark'] = SalesRebateConfig::UID_TYPE[$_v['type']];
                if (isset($singleCoupon[$_v['coupon_id']])) {
                    $_v['coupon'] = $singleCoupon[$_v['coupon_id']]['coupon_code'];
                } else {
                    if (isset($coupon[$_v['uid']]['person_coupon_id'])) {
                        $_v['coupon'] = $coupon[$_v['uid']]['person_coupon_code'];
                    } else if (isset($coupon[$_v['uid']]['company_coupon_id'])) {
                        $_v['coupon'] = $coupon[$_v['uid']]['company_coupon_code'];
                    }
                }
                if (isset($goods[$_v['goods_id']])) {
                    $_v['goods_title'] = $goods[$_v['goods_id']]['title'];
                    $_v['goods_img_url'] = $goods[$_v['goods_id']]['spec_img_url'];
                }
                if (isset($user[$_v['uid']])) {
                    $_v['nick'] = $user[$_v['uid']]['nick'];
                } else {
                    $_v['nick'] = '';
                }
                //返佣金额
                $_v['rebate'] = bcmul($_v['sale_amount'], $_v['rate'] / 100, 2);
                if (isset($orderData) && isset($orderData[$_v['order_no']])) {
                    $_v['order_addtime'] = $orderData[$_v['order_no']]['addtime'];
                }
                if ($step <> '' && ($step == 2 || $step == 3)) {
                    if (empty($order) || !in_array($_v['order_no'], $order)) {
                        $where['order_no[!]'][] = $_v['order_no'];
                        unset($data[$_k]);
                    }
                    if (isset($orderData) && isset($orderData[$_v['order_no']])) {
                        $nowTime = time();
                        $_v['last_time'] = '';
                        if ($step == 2) {
                            $_v['confirm_time'] = $orderData[$_v['order_no']]['confirm_time'];
                            if ((strtotime($orderData[$_v['order_no']]['confirm_time']) + mOrder::MAX_WAIT_AUTO_CONFIRM_TIME - $nowTime) > 0) {
                                $_v['last_time'] = ceil((strtotime($orderData[$_v['order_no']]['confirm_time']) + mOrder::MAX_WAIT_AUTO_CONFIRM_TIME - $nowTime) / 86400) . '天';
                            }
                        } else if ($step == 3) {
                            if (strtotime($orderData[$_v['order_no']]['delivery_time']) > 0) {
                                $_v['delivery_time'] = $orderData[$_v['order_no']]['delivery_time'];
                            } else {
                                $_v['delivery_time'] = '未发货';
                            }
                            if ((strtotime($orderData[$_v['order_no']]['delivery_time']) + mOrder::MAX_WAIT_AUTO_CONFIRM_TIME - $nowTime) > 0) {
                                $_v['last_time'] = ceil((strtotime($orderData[$_v['order_no']]['delivery_time']) + mOrder::MAX_WAIT_AUTO_CONFIRM_TIME - $nowTime) / 86400) . '天';
                            }
                        }
                    }
                }
                if ($isAdmData) {
                    $orderGoodsInfo = mOrderGoods::get([
                        'order_no',
                        'sku_id',
                        'commission_rate'
                    ], [
                        'order_no' => $_v['order_no'],
                        'sku_id' => $_v['sku_id']
                    ]);
                    $_v['order_rate'] = !empty($orderGoodsInfo) ? $orderGoodsInfo['commission_rate'] : null;
                    $operateCount = mSalesOrderLog::getOperateCount($_v['id']);
                    $_v['operate_count'] = $operateCount;
                }
            }
        }
        $result['list'] = array_values($data);
        unset($where['ORDER'], $where['LIMIT']);
        $result['is_over'] = bcsub(bcdiv(mSalesOrder::count('*', $where), $pagesize), $page) > 0 ? 0 : 1;
        $result['total'] = !empty($data) ? mSalesOrder::count('id', $where) : 0;

        return $result;
    }

    public static function admExportOrder($where, $params)
    {
        $data = [];
        $step = $params['step'];
        if ($step) {
            unset($where['LIMIT']);
            $result = self::getOrder($where, 0, 20, $step, $params, true);
            if ($result && $result['list']) {
                $headers = [];
                $letter = range('A', 'L');
                switch ($step) {
                    case 1:
                        $headers = [
                            'id',
                            'uid',
                            '设计师',
                            '返佣码类型',
                            '返佣码',
                            '订单号',
                            '商品',
                            '订单金额',
                            '返佣金',
                            '下单时间',
                            '返佣时间',
                            '状态'
                        ];
                        break;
                    case 2:
                        $headers = [
                            'id',
                            'uid',
                            '设计师',
                            '返佣码类型',
                            '返佣码',
                            '订单号',
                            '商品',
                            '订单金额',
                            '返佣金',
                            '下单时间',
                            '确认收货时间',
                            '入账倒计时',
                            '状态'
                        ];
                        $letter = range('A', 'M');
                        break;
                    case 3:
                        $headers = [
                            'id',
                            'uid',
                            '设计师',
                            '返佣码类型',
                            '返佣码',
                            '订单号',
                            '商品',
                            '订单金额',
                            '返佣金',
                            '下单时间',
                            '发货时间',
                            '确认收货时间',
                            '状态'
                        ];
                        $letter = range('A', 'M');
                        break;
                }
                if ($headers) {
                    $excelObj = new DownExcel();
                    $excelObj->setFileName('返佣记录' . time());
                    $excelObj->setSheetTitle('返佣记录');
                    //设置列宽
                    $widths = [
                        'A' => 20,
                        'B' => 20,
                        'C' => 30,
                        'D' => 20,
                        'E' => 30,
                        'F' => 35,
                        'G' => 20,
                        'H' => 20,
                        'I' => 20,
                        'J' => 20,
                        'K' => 20,
                        'L' => 20,
                    ];
                    if ($step != 1) {
                        $widths['M'] = 20;
                    } else {
                        unset($widths['M']);
                    }
                    $excelObj->setWidth($widths);
                    //默认单元格居中
                    $excelObj->setDefaultStyleAlignment();

                    $excelObj->setTextFormat('A');
                    $excelObj->setTextFormat('B');
                    $excelObj->setTextFormat('C');
                    $excelObj->setTextFormat('D');
                    $excelObj->setTextFormat('E');
                    $excelObj->setTextFormat('F');
                    $excelObj->setTextFormat('G');
                    $excelObj->setTextFormat('H');
                    $excelObj->setTextFormat('I');
                    $excelObj->setTextFormat('J');
                    $excelObj->setTextFormat('K');
                    foreach ($result['list'] as $row) {
                        $info = [
                            'id' => $row['id'],
                            'uid' => $row['uid'],
                            'nick' => $row['nick'],
                            'type_remark' => $row['type_remark'],
                            'coupon' => $row['coupon'],
                            'order_no' => $row['order_no'],
                            'goods_title' => $row['goods_title'],
                            'sale_amount' => $row['sale_amount'],
                            'rebate' => $row['rebate'],
                            'order_addtime' => $row['order_addtime'],
                        ];
                        switch ($step) {
                            case 1:
                                $info['edittime'] = $row['edittime'];
                                break;
                            case 2:
                                $info['confirm_time'] = $row['confirm_time'];
                                $info['last_time'] = $row['last_time'];
                                break;
                            case 3:
                                $info['delivery_time'] = $row['delivery_time'];
                                $info['last_time'] = $row['last_time'];
                                break;
                        }
                        $info['status_remark'] = $row['status_remark'];
                        $data[] = $info;
                    }
                    foreach ($letter as $key => $value) {
                        //设置字体
                        $excelObj->setFrontName($letter[$key]);
                        //设置加粗
                        $excelObj->setFrontBold("$letter[$key]1");
                        //设置大小
                        $excelObj->setFrontSize($letter[$key]);
                    }
                    $excelObj->create($data, $headers);
                }
            }
        }
    }

    public static function admExportAccounts()
    {
        $list = [];
        $data = mSalesAccount::getAllByWhere('*');
        if ($data) {
            $bank = [];
            foreach ($data as $_k => &$_v) {
                if ($_v['type'] == 1) {
                    $types[1][] = $_v['uid'];
                } else {
                    $types[2][] = $_v['uid'];
                }
            }
            if (isset($types[1])) {
                $bank['person'] = mSalesPersonal::getAllByWhere([
                    'uid',
                    'status'
                ], ['uid' => $types[1]]);
                $bank['person'] = array_column($bank['person'], 'status', 'uid');
            }
            if (isset($types[2])) {
                $bank['company'] = mSalesCompany::getAllByWhere([
                    'uid',
                    'status'
                ], ['uid' => $types[2]]);
                $bank['company'] = array_column($bank['company'], 'status', 'uid');
            }
            $userId = array_column($data, 'uid');
            $coupon = mSalesCoupon::getCache($userId);
            $coupon = array_column($coupon, NULL, 'uid');
            if (empty($params)) {
                $user = cSalesRebate::getUser(['uid' => $userId]);
            }

            $list = array_map(
                function ($_data) use ($user, $coupon, $bank) {
                    if (isset($coupon[$_data['uid']])) {
                        $_data['code'] = $_data['type'] == 1 ? $coupon[$_data['uid']]['person_coupon_code'] : $coupon[$_data['uid']]['company_coupon_code'];
                    }
                    if (isset($user[$_data['uid']])) {
                        $_data['nick'] = $user[$_data['uid']]['nick'];
                    }
                    $_data['bank_remark'] = '未提交';
                    if ($_data['type'] == 1) {
                        $total[$_data['uid']][] = $_data['sale_amount'];
                        if (isset($bank['person'][$_data['uid']])) {
                            $_data['bank_remark'] = cSalesRebate::getStatus($bank['person'][$_data['uid']], 2, 1);
                        }
                        $_data['type_remark'] = '个人账户';
                    } else {
                        $total[$_data['uid']][] = $_data['sale_amount'];
                        if (isset($bank['company'][$_data['uid']])) {
                            $_data['bank_remark'] = cSalesRebate::getStatus($bank['company'][$_data['uid']], 2, 2);
                        }
                        $_data['type_remark'] = '公司账户';
                    }

                    $_data['total'] = isset($total[$_data['uid']]) ? array_sum($total[$_data['uid']]) : 0;

                    return $_data;
                },
                $data
            );
        }
        if ($list) {
            $headers = [];
            $letter = range('A', 'I');
            $headers = [
                'id',
                'uid',
                '设计师',
                '类别',
                '返佣码',
                '销售总金额',
                '返佣金额',
                '已返佣金额',
                '认证状态'
            ];
            $excelObj = new DownExcel();
            $excelObj->setFileName('设计师返佣-账户信息');
            $excelObj->setSheetTitle('设计师返佣-账户信息');
            //设置列宽
            $widths = [
                'A' => 15,
                'B' => 20,
                'C' => 30,
                'D' => 20,
                'E' => 25,
                'F' => 30,
                'G' => 30,
                'H' => 30,
                'I' => 25,
            ];
            $excelObj->setWidth($widths);
            //默认单元格居中
            $excelObj->setDefaultStyleAlignment();

            $excelObj->setTextFormat('A');
            $excelObj->setTextFormat('B');
            $excelObj->setTextFormat('C');
            $excelObj->setTextFormat('D');
            $excelObj->setTextFormat('E');
            $excelObj->setTextFormat('F');
            $excelObj->setTextFormat('G');
            $excelObj->setTextFormat('H');
            $excelObj->setTextFormat('I');
            $exportData = [];
            foreach ($list as $row) {
                $info = [
                    'id' => $row['id'],
                    'uid' => $row['uid'],
                    'nick' => $row['nick'],
                    'type_remark' => $row['type_remark'],
                    'code' => $row['code'],
                    'sale_amount' => $row['order_no'],
                    'balance' => $row['balance'],
                    'sale_amount' => $row['sale_amount'],
                    'total_withdrawal_amount' => $row['total_withdrawal_amount'],
                    'bank_remark' => $row['bank_remark'],
                ];
                $exportData[] = $info;
            }
            foreach ($letter as $key => $value) {
                //设置字体
                $excelObj->setFrontName($letter[$key]);
                //设置加粗
                $excelObj->setFrontBold("$letter[$key]1");
                //设置大小
                $excelObj->setFrontSize($letter[$key]);
            }
            $excelObj->create($exportData, $headers);
        }
    }

    public static function getRebateInfosByCouponIds($couponIds)
    {
        $formatData = [];
        if ($couponIds) {
            $coupons = mSalesCouponMap::getCouponsByCouponId($couponIds);
            if ($coupons) {
                $uids = array_column($coupons, 'uid');
                $accountInfos = mSalesAccount::getAccountInfosByUids($uids);
                foreach ($coupons as $coupon) {
                    if (isset($accountInfos[$coupon['uid']][$coupon['coupon_type']])) {
                        $formatData[$coupon['coupon_id']] = [
                            'uid' => $coupon['uid'],
                            'rebate_pct' => $accountInfos[$coupon['uid']][$coupon['coupon_type']]['rebate_pct'],
                            'type' => $coupon['coupon_type'],
                            'coupon_id' => $coupon['coupon_id'],
                            'coupon_code' => $coupon['coupon_code']
                        ];
                    }
                }
            }
        }
        return $formatData;
    }


    /**
     * 获取券码信息
     * @param $params
     * @return $data
     */
    public static function getCode($couponIds)
    {
        $data = [];
        //获取主要券
        $coupons = [];
        $coupons = mSalesCoupon::select('*',
            [
                'OR' => [
                    'person_coupon_id' => $couponIds,
                    'company_coupon_id' => $couponIds,
                ]
            ]
        );
        //获取单次券
        $couponsSingle = [];
        $couponsSingle = mSalesCouponSingle::getAllByWhere('*', ['coupon_id' => $couponIds]);
        if (!empty($couponsSingle)) {
            $uid = array_column($couponsSingle, 'uid');
            $mainCoupon = mSalesCoupon::getAllByWhere([
                'uid',
                'status'
            ], ['uid' => $uid]);
            $mainCoupon = array_column($mainCoupon, NULL, 'uid');
        }

        if (!empty($coupons) && !empty($couponsSingle)) {
            $coupons = array_merge($coupons, $couponsSingle);
        } else if (empty($coupons) && !empty($couponsSingle)) {
            $coupons = $couponsSingle;
        }

        if (!empty($coupons)) {
            foreach ($coupons as $row) {
                $cCouponId = '';
                $cCouponCode = '';
                $pCouponId = '';
                $pCouponCode = '';
                if (isset($row['belong_type'])) {
                    $row['coupon_single'] = 1;
                    if (isset($mainCoupon[$row['uid']])) {
                        $row['status'] = $mainCoupon[$row['uid']]['status'];
                    }
                    switch ($row['belong_type']) {
                        case mSalesAccount::TYPE_PERSONAL:
                            $pCouponId = $row['coupon_id'];
                            $pCouponCode = $row['coupon_code'];
                            break;
                        case mSalesAccount::TYPE_COMPANY:
                            $cCouponId = $row['coupon_id'];
                            $cCouponCode = $row['coupon_code'];
                            break;
                    };
                } else {
                    $row['coupon_single'] = 0;
                    $cCouponId = $row['company_coupon_id'];
                    $cCouponCode = $row['company_coupon_code'];
                    $pCouponId = $row['person_coupon_id'];
                    $pCouponCode = $row['person_coupon_code'];
                }
                if (in_array($cCouponId, $couponIds)) {
                    $data[] = [
                        'id' => $row['id'],
                        'uid' => $row['uid'],
                        'status' => $row['status'],
                        'status_remark' => cSalesRebate::getStatus($row['status'], 1),
                        'type' => mSalesAccount::TYPE_COMPANY,
                        'coupon_id' => $cCouponId,
                        'coupon_code' => $cCouponCode,
                        'coupon_single' => $row['coupon_single'],
                    ];
                }
                if (in_array($pCouponId, $couponIds)) {
                    $data[] = [
                        'id' => $row['id'],
                        'uid' => $row['uid'],
                        'status' => $row['status'],
                        'status_remark' => cSalesRebate::getStatus($row['status'], 1),
                        'type' => mSalesAccount::TYPE_PERSONAL,
                        'coupon_id' => $pCouponId,
                        'coupon_code' => $pCouponCode,
                        'coupon_single' => $row['coupon_single'],
                    ];
                }

            }
        }
        return $data;
    }

    /**
     * 后台管理系统：获取白名单
     * */
    public static function getCoupon($where = '', $params = '')
    {
        if (!empty($params)) {
            $user = cSalesRebate::getUser($params);
            if (!empty($user)) {
                $userId = array_column($user, 'uid');
                $where['uid'] = $userId;
            }
        }

        $data = [];
        $data = mSalesCoupon::getAllByWhere('*', $where);

        if ($data) {
            //用户姓名
            if (empty($params)) {
                $user = array_unique(array_column($data, 'uid'));
                $user = cSalesRebate::getUser(['uid' => $user]);
            }
            $result['list'] = array_map(
                function ($_data) use ($user) {
                    $_data['status_remark'] = cSalesRebate::getStatus($_data['status'], 1);
                    if (isset($user[$_data['uid']])) {
                        $_data['nick'] = $user[$_data['uid']]['nick'];
                        $_data['telephone'] = $user[$_data['uid']]['telephone'];
                    }
                    return $_data;
                },
                $data
            );
        } else {
            $result['list'] = [];
        }
        unset($where['ORDER'], $where['LIMIT']);
        $result['total'] = mSalesCoupon::count('id', $where);

        return $result;
    }

    /**
     * 后台管理系统：获取单次券
     * */
    public static function getCouponSingle($where = '')
    {
        $data = [];
        $data = mSalesCouponSingle::getAllByWhere('*', $where);

        if ($data) {
            $coupon_id = array_column($data, 'coupon_id');
            //获取优惠券信息
            $coupons = mCouponConfig::select('*', ['coupon_id' => $coupon_id]);
            $coupons = array_column($coupons, NULL, 'coupon_id');
            //获取使用优惠券的信息
            $salesOrder = mSalesOrder::getAllByWhere([
                'coupon_id',
                'order_no'
            ], ['coupon_id' => $coupon_id]);
            if (!empty($salesOrder)) {
                $salesOrder = array_column($salesOrder, 'order_no', 'coupon_id');
            }

            foreach ($data as $_k => &$_v) {
                $data[$_k]['order_no'] = '';

                if (isset($coupons[$_v['coupon_id']])) {
                    $data[$_k]['full_amount'] = $coupons[$_v['coupon_id']]['full_amount'];
                    $data[$_k]['discount_level'] = $coupons[$_v['coupon_id']]['discount_level'];
                    $data[$_k]['start_time'] = $coupons[$_v['coupon_id']]['start_time'];
                    $data[$_k]['stop_time'] = $coupons[$_v['coupon_id']]['stop_time'];
                }
                if (isset($salesOrder[$_v['coupon_id']])) {
                    $data[$_k]['order_no'] = $salesOrder[$_v['coupon_id']];
                }
            }

            $result['list'] = $data;
        } else {
            $result['list'] = [];
        }
        unset($where['ORDER'], $where['LIMIT']);
        $result['total'] = mSalesCouponSingle::count('id', $where);

        return $result;
    }

    /**
     * 后台管理系统：获取账户列表信息
     * */
    public static function getAccountList($where = '', $params = [])
    {
        if (!empty($params)) {
            $user = cSalesRebate::getUser($params);
            if (!empty($user)) {
                $userId = array_column($user, 'uid');
                $where['uid'] = $userId;
            }
        }

        $data = [];
        $data = mSalesAccount::getAllByWhere('*', $where);
        if ($data) {
            $bank = [];
            foreach ($data as $_k => &$_v) {
                if ($_v['type'] == 1) {
                    $types[1][] = $_v['uid'];
                } else {
                    $types[2][] = $_v['uid'];
                }
            }
            if (isset($types[1])) {
                $bank['person'] = mSalesPersonal::getAllByWhere([
                    'uid',
                    'status'
                ], ['uid' => $types[1]]);
                $bank['person'] = array_column($bank['person'], 'status', 'uid');
            }
            if (isset($types[2])) {
                $bank['company'] = mSalesCompany::getAllByWhere([
                    'uid',
                    'status'
                ], ['uid' => $types[2]]);
                $bank['company'] = array_column($bank['company'], 'status', 'uid');
            }
            $userId = array_column($data, 'uid');
            $coupon = mSalesCoupon::getCache($userId);
            $coupon = array_column($coupon, NULL, 'uid');
            if (empty($params)) {
                $user = cSalesRebate::getUser(['uid' => $userId]);
            }

            $result['list'] = array_map(
                function ($_data) use ($user, $coupon, $bank) {
                    if (isset($coupon[$_data['uid']])) {
                        $_data['code'] = $_data['type'] == 1 ? $coupon[$_data['uid']]['person_coupon_code'] : $coupon[$_data['uid']]['company_coupon_code'];
                    }
                    if (isset($user[$_data['uid']])) {
                        $_data['nick'] = $user[$_data['uid']]['nick'];
                    }
                    $_data['bank_remark'] = '未提交';
                    if ($_data['type'] == 1) {
                        $total[$_data['uid']][] = $_data['sale_amount'];
                        if (isset($bank['person'][$_data['uid']])) {
                            $_data['bank_remark'] = cSalesRebate::getStatus($bank['person'][$_data['uid']], 2, 1);
                        }
                        $_data['type_remark'] = '个人账户';
                    } else {
                        $total[$_data['uid']][] = $_data['sale_amount'];
                        if (isset($bank['company'][$_data['uid']])) {
                            $_data['bank_remark'] = cSalesRebate::getStatus($bank['company'][$_data['uid']], 2, 2);
                        }
                        $_data['type_remark'] = '公司账户';
                    }

                    $_data['total'] = isset($total[$_data['uid']]) ? array_sum($total[$_data['uid']]) : 0;

                    return $_data;
                },
                $data
            );
        } else {
            $result['list'] = [];
        }
        unset($where['ORDER'], $where['LIMIT']);
        $result['total'] = mSalesAccount::count('id', $where);

        return $result;
    }

    /**
     * 后台管理系统： 获取银行账户
     * */
    public static function getBank($uid, $type)
    {
        $data = [];
        $result = [];
        if ($type == 1) {
            $data = cSalesRebate::getAccount($uid, 1);
            $header = [
                'name' => '姓名',
                'id_card_no' => '身份证',
                'bank_no' => '卡号',
                'telephone' => '电话',
                'status_remark' => '状态'
            ];
            $result['header'] = array_values($header);
            if (!empty($data)) {
                $data['status_remark'] = cSalesRebate::getStatus($data['status'], 2, 1);
            }
        } else {
            $data = cSalesRebate::getAccount($uid, 2);
            $header = [
                'name' => '公司',
                'bank_no' => '卡号',
                'bank_name' => '银行',
                'province' => '省',
                'city' => '市',
                'area' => '区',
                'subbranch' => '支行',
                'status_remark' => '状态'
            ];
            $result['header'] = array_values($header);
            if (!empty($data)) {
                $data['status_remark'] = cSalesRebate::getStatus($data['status'], 2, 2);
            }
        }
        if (!empty($data)) {
            foreach ($data as $_k => &$_v) {
                if (!in_array($_k, array_keys($header))) {
                    unset($data[$_k]);
                    continue;
                } else {
                    switch ($_k) {
                        case 'province':
                            $_v = ShopArea::getInfoByCode($_v)['province_name'];
                            break;
                        case 'city':
                            $_v = ShopArea::getInfoByCode($_v)['city_name'];
                            break;
                        case 'area':
                            $_v = ShopArea::getInfoByCode($_v)['area_name'];
                            break;
                    }
                }
            }
        }

        $result['list'] = !empty($data) ? [$data] : [];

        return $result;
    }

}
